<template>
  <div class="page-modal">
    <el-dialog
      v-model="dialogVisible"
      title="Tips"
      width="30%"
      destroy-on-close
    >
      <MieForm
        :form-items="pageModalConfig.formItems"
        :col-layout="pageModalConfig.colLayout"
        :item-style="pageModalConfig.itemStyle"
        v-model="formData"
      ></MieForm>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleCreateUser"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import useSystemStore from "@/stores/main/system/system";
import useMainStore from "@/stores/main/main";
import MieForm from "@/base-ui/form";

interface IPageModelProps {
  pageModalConfig?: any;
  defaultInfo?: any;
  otherInfo?: any;
}
const props = withDefaults(defineProps<IPageModelProps>(), {
  pageModalConfig: () => ({}),
  defaultInfo: () => ({}),
  otherInfo: () => ({}),
});

// 输入框基本数据
let formData = ref<any>({});
watch(
  () => props.defaultInfo,
  (newValue) => {
    for (const item of props.pageModalConfig.formItems) {
      formData.value[item.fileId] = props.defaultInfo[item.fileId];
    }
  }
);

// 弹窗控制
const dialogVisible = ref(false);
const systemStore = useSystemStore();
const cancel = () => {
  dialogVisible.value = false;
};
//点击确定按钮,创建数据,编辑数据
const handleCreateUser = async () => {
  console.log(props.defaultInfo);
  if (Object.keys(props.defaultInfo).length) {
    await systemStore.editAction(
      props.pageModalConfig.pageName,
      { ...formData.value, ...props.otherInfo },
      props.defaultInfo.id
    );
  } else {
    await systemStore.createAction(props.pageModalConfig.pageName, {
      ...formData.value,
      ...props.otherInfo,
    });
  }
  dialogVisible.value = false;

  switch (props.pageModalConfig.pageName) {
    case "map":
      useMainStore().getCategoryDataAction();
      break;
    case "role":
      useMainStore().getRoleDataAction();
      break;
    case "category":
      useMainStore().getCategoryDataAction();
      break;
    case "car":
      useMainStore().getCarDataAction();
      break;
    case "menber":
      useMainStore().getMenberDataAction();
      break;
    default:
      break;
  }
};

defineExpose({ dialogVisible });
</script>

<style lang="less" scoped></style>
